import React from 'react';
import BreadcrumbCustom from './BreadcrumbCustom';
import {Row, Col, message, Form, Input, Button} from 'antd';
import {fetchData} from '@/action';
import qs from 'qs';
import * as Const from '../common/const';
import * as Request from '../Server/SystemManger';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import {bindActionCreators} from 'redux';

const FormItem = Form.Item;
const reg = /^(?!([A-Z]*|[a-z]*|[0-9]*|[!-/:-@\[-`{-~]*|[A-Za-z]*|[A-Z0-9]*|[A-Z!-/:-@\[-`{-~]*|[a-z0-9]*|[a-z!-/:-@\[-`{-~]*|[0-9!-/:-@\[-`{-~]*)$)[A-Za-z0-9!-/:-@\[-`{-~]{8,20}$/;

class ChangePwd extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: undefined
        };
    }

    componentWillMount() {
        const user = localStorage.getItem('user');
        if (user) {
            this.setState({username: JSON.parse(user).username})
        }
    }

    validatePassword = (rule, value, callback) => {
        if(!value || !value.length){callback();}
        if (!reg.test(value)) {
            callback('密码包含大写字母、小写字母、数字、特殊符号中的至少三类，且长度在8到20之间!');
            return;
        } else {
            callback();
        }
        if(this.props.form.getFieldValue('confirmPassword')){
            this.props.form.validateFields(['confirmPassword'],{ force: true });
        }
    }

    compareToFirstPassword = (rule, value, callback) => {
        const form = this.props.form;
        const password = form.getFieldValue('password');
        if(!password || !password.length){callback();}
        if(!value || !value.length){callback();}
        if (value && value !== password) {
            callback('两次输入的密码不一致!');
        } else {
            callback();
        }
    }

    handleSubmit = (e) => {
        const _this = this;
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
           if (!err) {
                const params = {username: _this.state.username, ...values};
                delete params.confirmPassword;
                Request.updatePwd(qs.stringify(params)).then(res => {
                    if (res && Const.REQUEST_SUCCESS == res.code) {
                        _this.logout();
                        message.success('修改成功,请重新登录!',2);
                    }else{
                        res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg,2);
                    }
                });
            }
        });
    }

    logout = () => {
        const {fetchData} = this.props
        fetchData({funcName: 'logout'}).then((res) => {
            if (res && res.data && Const.REQUEST_SUCCESS == res.data.code) {
                localStorage.removeItem('user');
                this.props.history.push('/login');
            }
        })
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 8},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 8},
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 16,
                    offset: 11,
                },
            },
        };
        return (
            <div>
                <BreadcrumbCustom first={'修改密码'}/>
                <Form style={{paddingTop: '8%'}} onSubmit={this.handleSubmit}>
                    <Row><Col span={24}>
                        <FormItem {...formItemLayout}
                                  label="原密码"
                        >
                            {getFieldDecorator('oldPassword', {
                                rules: [{
                                    required: true, message: '请输入原密码!',
                                }],
                            })(
                                <Input type={'password'} maxLength={255}/>
                            )}
                        </FormItem>
                    </Col></Row>
                    <Row><Col span={24}>
                        <FormItem {...formItemLayout}
                                  label="新密码"
                        >
                            {getFieldDecorator('password', {
                                rules: [{
                                    required: true, message: '请输入新密码!',
                                }, {
                                    validator: this.validatePassword,
                                }]
                            })(
                                <Input type={'password'} maxLength={255}/>
                            )}
                        </FormItem>
                    </Col></Row><Row><Col span={24}>
                    <FormItem {...formItemLayout}
                              label="确认密码"
                    >
                        {getFieldDecorator('confirmPassword', {
                            rules: [{
                                required: true, message: '请再次输入密码确认!',
                            }, {
                                validator: this.compareToFirstPassword,
                            }]
                        })(
                            <Input type={'password'} maxLength={255}/>
                        )}
                    </FormItem>
                </Col></Row><Row><Col span={24}>
                    <FormItem {...tailFormItemLayout}>
                        <Button type="primary" htmlType="submit">修改密码</Button>
                    </FormItem>
                </Col></Row>
                </Form>
                <style>{`
                    .ant-form-item{
                            padding: 10px 0;
                }
                `}</style>
            </div>
        );
    }
}

const ChangePwdForm = Form.create()(ChangePwd);

const mapStateToProps = state => {
    const {responsive = {data: {}}} = state.httpData;
    return {responsive};
};
const mapDispatchToProps = dispatch => ({
    fetchData: bindActionCreators(fetchData, dispatch),
});
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ChangePwdForm));


